package handler

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"

	"yanxue_ai_go/services/gateway/internal/proxy"
	"yanxue_ai_go/services/gateway/internal/service"
)

// GatewayHandler 网关处理器
type GatewayHandler struct {
	serviceProxy *proxy.ServiceProxy
	authService  *service.AuthService
	upgrader     websocket.Upgrader
}

// NewGatewayHandler 创建网关处理器
func NewGatewayHandler(serviceProxy *proxy.ServiceProxy, authService *service.AuthService) *GatewayHandler {
	return &GatewayHandler{
		serviceProxy: serviceProxy,
		authService:  authService,
		upgrader: websocket.Upgrader{
			CheckOrigin: func(r *http.Request) bool {
				return true // 在生产环境中应该进行适当的检查
			},
		},
	}
}

// Login 用户登录
func (h *GatewayHandler) Login(c *gin.Context) {
	var req struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	token, err := h.authService.Login(req.Username, req.Password)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"token": token,
		"type":  "Bearer",
	})
}

// Register 用户注册
func (h *GatewayHandler) Register(c *gin.Context) {
	var req struct {
		Username string `json:"username" binding:"required"`
		Email    string `json:"email" binding:"required,email"`
		Password string `json:"password" binding:"required,min=6"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	err := h.authService.Register(req.Username, req.Email, req.Password)
	if err != nil {
		c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"message": "User registered successfully"})
}

// RefreshToken 刷新令牌
func (h *GatewayHandler) RefreshToken(c *gin.Context) {
	var req struct {
		RefreshToken string `json:"refresh_token" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	newToken, err := h.authService.RefreshToken(req.RefreshToken)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid refresh token"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"token": newToken,
		"type":  "Bearer",
	})
}

// Logout 用户登出
func (h *GatewayHandler) Logout(c *gin.Context) {
	token := c.GetHeader("Authorization")
	if token != "" && strings.HasPrefix(token, "Bearer ") {
		token = token[7:]
		h.authService.RevokeToken(token)
	}

	c.JSON(http.StatusOK, gin.H{"message": "Logged out successfully"})
}

// ProxyToAgent 代理到Agent服务
func (h *GatewayHandler) ProxyToAgent(c *gin.Context) {
	path := "/api/v1/agents" + c.Param("path")
	h.serviceProxy.ForwardRequestWithBody(c, "agent", path)
}

// ProxyToMCP 代理到MCP服务
func (h *GatewayHandler) ProxyToMCP(c *gin.Context) {
	path := "/api/v1/mcp" + c.Param("path")
	h.serviceProxy.ForwardRequestWithBody(c, "mcp", path)
}

// ProxyToRAG 代理到RAG服务
func (h *GatewayHandler) ProxyToRAG(c *gin.Context) {
	path := "/api/v1/rag" + c.Param("path")
	h.serviceProxy.ForwardRequestWithBody(c, "rag", path)
}

// GetServicesStatus 获取所有服务状态
func (h *GatewayHandler) GetServicesStatus(c *gin.Context) {
	// 从服务注册中心获取服务状态
	services := map[string]interface{}{
		"agent": map[string]interface{}{
			"status": "healthy",
			"uptime": "2h30m",
		},
		"mcp": map[string]interface{}{
			"status": "healthy",
			"uptime": "2h30m",
		},
		"rag": map[string]interface{}{
			"status": "healthy",
			"uptime": "2h30m",
		},
	}

	c.JSON(http.StatusOK, gin.H{
		"services": services,
		"gateway":  "healthy",
	})
}

// ProxyWebSocket WebSocket代理
func (h *GatewayHandler) ProxyWebSocket(c *gin.Context) {
	// 升级到WebSocket连接
	conn, err := h.upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Failed to upgrade to WebSocket"})
		return
	}
	defer conn.Close()

	// 这里实现WebSocket代理逻辑
	// 暂时返回简单响应
	conn.WriteJSON(gin.H{
		"message": "WebSocket connection established",
		"path":    c.Param("path"),
	})
}

// PrometheusMetrics Prometheus监控指标
func (h *GatewayHandler) PrometheusMetrics(c *gin.Context) {
	// 这里应该返回Prometheus格式的指标
	// 暂时返回简单的文本
	metrics := `# HELP gateway_requests_total Total number of requests
# TYPE gateway_requests_total counter
gateway_requests_total{service="gateway"} 100

# HELP gateway_request_duration_seconds Request duration in seconds
# TYPE gateway_request_duration_seconds histogram
gateway_request_duration_seconds_bucket{le="0.1"} 80
gateway_request_duration_seconds_bucket{le="0.5"} 95
gateway_request_duration_seconds_bucket{le="1.0"} 98
gateway_request_duration_seconds_bucket{le="+Inf"} 100
gateway_request_duration_seconds_sum 45.2
gateway_request_duration_seconds_count 100
`

	c.Header("Content-Type", "text/plain")
	c.String(http.StatusOK, metrics)
}
